package com.imageim.yimirror.base;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.view.MotionEvent;
import android.view.View;

import com.imageim.yimirror.R;
import com.imageim.yimirror.common.EnviromentConfig;
import com.imageim.yimirror.common.event.EventCode;
import com.imageim.yimirror.common.event.EventMessage;
import com.imageim.yimirror.common.ui.MultiResolutionUtil;
import com.imageim.yimirror.common.ui.dialog.LoadingDialog;
import com.imageim.yimirror.common.util.LogUtil;
import com.imageim.yimirror.common.util.SystemUtil;
import com.imageim.yimirror.common.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.Timer;
import java.util.TimerTask;

import cn.bingoogolapple.swipebacklayout.BGASwipeBackHelper;

/**
 * Created by Yuaihen on 2017/12/4.
 * Activity基类
 */

public abstract class BaseActivity extends FragmentActivity implements BGASwipeBackHelper.Delegate {

    protected Context mContext;
    private LoadingDialog loadingDialog;
    protected int screenWidth;
    protected int screenHeight;
    private static final int NAV_BAR_HEIGHT = 56;
    protected BGASwipeBackHelper mSwipeBackHelper;
    private boolean isSupportQuit; // 默认不支持倒计时自动退出
    private Timer quitTimer;
    private long quitTimeMillis = 1000 * 30;
    protected int toDoAction = 0;
//    protected String pageId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        initSwipeBackFinish();
        super.onCreate(savedInstanceState);
        mContext = this;
        dealWithVirtualNavBar();
        initAnim();
        setContentView(getLayoutId());
        EventBus.getDefault().register(this);
        initDialog();
        initBundle();
        initView();
        if (!EnviromentConfig.IS_MIRROR) {
            MultiResolutionUtil.adapterActivity(this);
        }
        initData();
        initListener();
        if (isSupportAutoQuit()) {
            initTimer();
        }
    }

    protected boolean isSupportAutoQuit() {
        return isSupportQuit;
    }

    protected long getQuitTimeMillis() {
        return quitTimeMillis;
    }

    private void initTimer() {
        quitTimer = new Timer();
        quitTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                finish();
            }
        }, getQuitTimeMillis());
    }

    public void stopQuitTimer() {
        if (quitTimer != null) {
            quitTimer.cancel();
            quitTimer = null;
        }
    }

    protected void initListener() {

    }

    private void dealWithVirtualNavBar() {
        if (SystemUtil.hasNavBar(this)) {
            SystemUtil.hideBottomUIMenu(this);
            screenWidth = getScreenWidth();
            screenHeight = getScreenHeight() + NAV_BAR_HEIGHT;
        } else {
            screenWidth = getScreenWidth();
            screenHeight = getScreenHeight();
        }
        getWindow().getDecorView().setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    if (motionEvent.getY() < (3.0f / 4) * screenHeight) {
                        SystemUtil.hideBottomUIMenu((Activity) mContext);
                    }
                }
                return false;
            }
        });
        SystemUtil.autoHideNavBar(this);
    }

    private void initDialog() {
        loadingDialog = new LoadingDialog(this);
        loadingDialog.setMsg("");
        //        loadingDialog.setOnShowListener(new DialogInterface.OnShowListener() {
        //            @Override
        //            public void onShow(DialogInterface dialog) {
        //                if (SystemUtil.hasNavBar(mContext)) {
        //                    SystemUtil.hideBottomUIMenu(BaseActivity.this);
        //                }
        //            }
        //        });
        SystemUtil.hideNavBarWhenShowDialog(loadingDialog);
    }

    protected void initAnim() {

    }

    //Log打印
    protected void logD(String msg) {
        LogUtil.d(getClass().getSimpleName(), msg);
    }

    //Log打印
    protected void logE(String msg) {
        LogUtil.e(getClass().getSimpleName(), msg);
    }

    //Toast
    protected void toast(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtil.show(msg);
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (quitTimer != null) {
            quitTimer.cancel();
            quitTimer = null;
        }
    }

    @Subscribe()
    public void onEventMainThread(EventMessage event) {
        switch (event.getCode()) {
            case EventCode.CODE_FINISH_ALL:
                finish();
                break;
            default:
        }
    }


    @Subscribe(sticky = true)
    public void onEventSticky(EventMessage event) {
        switch (event.getCode()) {
            case EventCode.CODE_FINISH_ALL:
                finish();
                break;
            default:
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        SystemUtil.hideBottomUIMenu(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    protected abstract void initBundle();

    protected abstract int getLayoutId();

    protected abstract void initView();

    protected abstract void initData();

    public void showLoading() {
        if (!loadingDialog.isShowing() && !isFinishing()) {
            loadingDialog.setMsg(null);
            loadingDialog.show();
        }
    }

    public void showLoading(String msg) {
        if (!loadingDialog.isShowing() && !isFinishing()) {
            loadingDialog.setMsg(msg);
            loadingDialog.show();
        }
    }

    public void hideLoading() {
        loadingDialog.dismiss();
    }

    public int getScreenHeight() {
        return getWindowManager().getDefaultDisplay().getHeight();
    }

    public int getScreenWidth() {
        return getWindowManager().getDefaultDisplay().getWidth();
    }


    /**
     * 初始化滑动返回。在 super.onCreate(savedInstanceState) 之前调用该方法
     */
    private void initSwipeBackFinish() {
        mSwipeBackHelper = new BGASwipeBackHelper(this, this);

        // 「必须在 Application 的 onCreate 方法中执行 BGASwipeBackHelper.init 来初始化滑动返回」
        // 下面几项可以不配置，这里只是为了讲述接口用法。

        // 设置滑动返回是否可用。默认值为 true
        mSwipeBackHelper.setSwipeBackEnable(false);
        // 设置是否仅仅跟踪左侧边缘的滑动返回。默认值为 true
        mSwipeBackHelper.setIsOnlyTrackingLeftEdge(true);
        // 设置是否是微信滑动返回样式。默认值为 true
        mSwipeBackHelper.setIsWeChatStyle(true);
        // 设置阴影资源 id。默认值为 R.drawable.bga_sbl_shadow
        mSwipeBackHelper.setShadowResId(R.drawable.bga_sbl_shadow);
        // 设置是否显示滑动返回的阴影效果。默认值为 true
        mSwipeBackHelper.setIsNeedShowShadow(true);
        // 设置阴影区域的透明度是否根据滑动的距离渐变。默认值为 true
        mSwipeBackHelper.setIsShadowAlphaGradient(true);
        // 设置触发释放后自动滑动返回的阈值，默认值为 0.3f
        mSwipeBackHelper.setSwipeBackThreshold(0.3f);
        // 设置底部导航条是否悬浮在内容上，默认值为 false
        mSwipeBackHelper.setIsNavigationBarOverlap(false);
    }

    /**
     * 是否支持滑动返回。这里在父类中默认返回 true 来支持滑动返回，如果某个界面不想支持滑动返回则重写该方法返回 false 即可
     *
     * @return
     */
    @Override
    public boolean isSupportSwipeBack() {
        return true;
    }

    /**
     * 正在滑动返回
     *
     * @param slideOffset 从 0 到 1
     */
    @Override
    public void onSwipeBackLayoutSlide(float slideOffset) {
    }

    /**
     * 没达到滑动返回的阈值，取消滑动返回动作，回到默认状态
     */
    @Override
    public void onSwipeBackLayoutCancel() {
    }

    /**
     * 滑动返回执行完毕，销毁当前 Activity
     */
    @Override
    public void onSwipeBackLayoutExecuted() {
        mSwipeBackHelper.swipeBackward();
    }

    @Override
    public void onBackPressed() {
        // 正在滑动返回的时候取消返回按钮事件
        if (mSwipeBackHelper.isSliding()) {
            return;
        }
        mSwipeBackHelper.backward();
    }

}
